#include <webx/route.h>
#include <webx/route.h>

class ExportEntity : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(ExportEntity)

int ExportEntity::process()
{
	int res = 0;

	param_string(dbid);
	param_string(name);
	
	webx::CheckFileName(name);
	webx::CheckSystemRight(this);

	sp<DBConnect> dbconn = webx::GetDBConnect(dbid);
	sp<QueryResult> result = dbconn->query("SELECT * FROM " + name + " WHERE 1=0");

	if (!result) stdx::Throw(XG_ERROR, dbconn->getErrorString());

	res = result->cols();

	if (res > 0)
	{
		string line;
		string source;
		ColumnData item;

		for (int i = 0; i < res; i++)
		{
			if (result->getColumnData(item, i))
			{
				string name = item.name;

				switch(item.type)
				{
					case DBData_Float:
						line = "\trdouble(" + stdx::tolower(name) + ");\n";
						break;
					case DBData_Integer:
						line = "\trint(" + stdx::tolower(name) + ");\n";
						break;
					default:
						line = "\trstring(" + stdx::tolower(name) + ");\n";
						break;
				}

				source += line;
			}
		}

		stdx::toupper(name);
	
		string cls = "JsonEntity(Entity)";
		string inc = "#include <json/json.h>";
		string gap = "///////////////////////////////////////////////";
		string head = stdx::format("#ifndef XG_DBENTITY_%s_H\n#define XG_DBENTITY_%s_H", name.c_str(), name.c_str());

		source = stdx::format("%s\n%s\n%s\n\n%s\n{\npublic:\n%s};\n%s\n#endif",
					head.c_str(), gap.c_str(), inc.c_str(), cls.c_str(),
					source.c_str(), gap.c_str());

		json["content"] = source;
	}

	json["code"] = res;
	out << json;

	return XG_OK;
}